package cn.edu.xust.health.interceptor;

import cn.edu.xust.health.entity.User;
import cn.edu.xust.health.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

@Log
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler)
            throws Exception {
        log.info("拦截");
        String auth = req.getHeader("Authorization");
        if( auth == null ) {
            return false;
        }
        if( !auth.startsWith( "Bearer " ) ) {
            return false;
        }
        log.info( auth );
        String token = auth.substring( "Bearer ".length() );
        log.info( token );
        // 若 token 未能通过校验
        if( !tokenService.verify( token ) ) {
            return false;
        }
        User x = tokenService.parse(token);
        req.setAttribute( "user", x );
        return true;
    }
}
